// axios.js
import { getToken, removeToken, getLanguageCode } from "@/modules/auth";
import { showNotify } from "vant";
import { createFetch } from "@vueuse/core";
import { decryptByAES } from "./aesjs";
import { router } from "@/modules/router";


const baseURL = import.meta.env.VITE_APP_BASE_API;

const useMyFetch = createFetch({
  baseUrl: baseURL,
  options: {
    async beforeFetch({ options, cancel, url }) {
      const token = getToken();
      const languageCode = getLanguageCode();
      if (
        !token &&
        url != baseURL + "/api/user/touristLogin" &&
        url != baseURL + "/api/user/login" &&
        url != baseURL + "/api/user/register"
      ) {
        cancel();
      }
      options.headers.token = token;
      options.headers.languageCode = languageCode;
      return { options };
    },
    async afterFetch(response) {
      const encrypt = "1q2w3e4r5t6y7u8i";
      const res = decryptByAES(JSON.parse(response.data), encrypt, encrypt);
      const { code, data, msg } = JSON.parse(res); 
      if (code && code !== 20000) {
        showNotify({
          type: "danger",
          message: msg,
        });
        if (code == 401) {
          removeToken()
          router.push({ name: "login" });
        }
        response.data = JSON.parse(res);
      } else if (code && data) {
        response.data = JSON.parse(res);
      } else {
        response.data = JSON.parse(res);
      }
      return response;
    },
  },
  fetchOptions: {
    mode: "cors",
  },
});

/* post */
export function fetchPost(url, data) {
  const formData = new FormData();
  if (typeof data == "object") {
    for (let i in data) {
      formData.append(i, data[i]);
    }
  }
  return new Promise((resolve, reject) => {
    useMyFetch(url)
      .post(formData)
      .then((res) => {
        const data = res.data.value;
        if (data != null) {
          resolve(data);
        } else {
          const obj = {
            message: "error 500",
          };
          reject(obj);
        }
      });
  }).catch((error) => {
    showNotify({
      type: "danger",
      message: error.message,
    });
    return error;
  });
}

/* get */
export function fetchGet(url, param) {
  const formData = new FormData();
  if (typeof param == "object") {
    for (let i in param) {
      formData.append(i, param[i]);
    }
  }
  return new Promise((resolve, reject) => {
    useMyFetch(url)
      .post(formData)
      .then((res) => {
        const data = res.data.value;
        if (data != null) {
          resolve(data);
        } else {
          const obj = {
            message: "error 500",
          };
          reject(obj);
        }
      });
  }).catch((error) => {
    showNotify({
      type: "danger",
      message: error.message,
    });
    return error;
  });
}

/* 上传文件 */
export function fetchUpload(url, formData) {
  return new Promise((resolve, reject) => {
    useMyFetch(url)
      .post(formData)
      .then((res) => {
        const data = res.data.value;
        resolve(data);
      });
  });
}

/* 下载文件 */
// export function getFile(url, filename) {
//   return new Promise((resolve, reject) => {
//     service
//       .get(url, { responseType: "arraybuffer", responseType: "blob" })
//       .then((res) => {
//         resolve(res.data);
//       })
//       .catch((err) => {
//         reject(err);
//       });
//   });
// }
